#include <system.h>
#include <std.h>
#include <pio.h>
#include <error.h>
#include <pipe.h>

/*Concept:
Pipes will be used for interprocess communication. A process can create a communication pipe. Other processes
may join this pipe to communicate with each other.
For joining a pipe a process may ask for the pipes of any other process referring to it by it's name.
It may join the pipe by acquiring the handle of the pipe.
*/

static struct pipe *head;

struct pipe *create_pipe()
{
	int i;
	struct pipe *temp;
	temp=(struct pipe *)get_mem(sizeof(struct pipe));
	for(i=0;i<64;i++)
		temp->q[i]=NULL;
	temp->rear=NULL;
	i=add_pipe_process(temp);
	if(i==SUCCESS)
		return temp;
	else	{		//The pipe failed to register in the process...
		free(temp);
		return NULL;
	}
}

int send_pipe(struct pipe *temp,unsigned long msg)
{
	if((temp->rear)>=MAXQ)
		return FAILED;
	temp->q[temp->rear]=msg;
	temp->rear++;
	return SUCCESS;
}

unsigned long receive_pipe(struct pipe *temp)
{
	int i;
	unsigned long ret;
	if((temp->rear)<=0)
		return NULL;
	ret=temp->q[0];
	for(i=0;i<(temp->rear);i++)
		temp->q[i]=temp->q[i+1];
	temp->q[temp->rear]=NULL;
	temp->rear--;
	return ret;
}

int clear_pipe(struct pipe *temp)
{
	int i;
	for(i=0;i<MAXQ;i++)
		temp->q[i]=NULL;
	temp->rear=NULL;
	return SUCCESS;
}

int pipe_state(struct pipe *temp)
{
	return temp->rear;
}
